package com.example.sjh_web

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Looper
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.DownloadListener
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.example.sjh_web.other.sjh_SDFileHelper
import com.example.sjh_web.sjh_SunnyWeatherApplication.Companion.context
import com.example.sjh_web.weather.model.Location
import com.example.sjh_web.weather.model.Place
import com.example.sjh_web.weather.model.getSky
import kotlinx.android.synthetic.main.nav_header.*
import kotlinx.android.synthetic.main.nav_header.view.*
import kotlinx.android.synthetic.main.sjh_main_activity.*
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread


class sjh_MainActivity : AppCompatActivity() {

    var mLocationClient: LocationClient? = null
    private val myListener: MyLocationListener = MyLocationListener()
    private var place: Place? = null

    @SuppressLint("SetJavaScriptEnabled", "ResourceAsColor")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.sjh_main_activity)
        val headview = navView.inflateHeaderView(R.layout.nav_header)   //动态加载headerLayout，使headerLayout中的控件能响应点击
        webView.settings.javaScriptEnabled = true
        webView.webViewClient = WebViewClient()
        webView.loadUrl("http://hao.uc.cn")

        //下载文件时，跳转到系统浏览器进行下载
        webView.setDownloadListener(MyWebViewDownLoadListener())

        // 5.0以上是默认不允许用安全的来源里加载不安全的资源，某些资源图片是HTTP，因此进行以下设置
        val webSetting: WebSettings = webView.getSettings()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        //定位权限的获取，用于天气处理
        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION),
                1
            )
        }
        else {
            getcity()
        }

        //底部菜单栏点击事件
        bottom_navigation.setOnNavigationItemSelectedListener() {
            when(it.itemId){
                R.id.navigation -> drawLayout.openDrawer(GravityCompat.START)  //打开左侧菜单栏
                R.id.back -> webView.goBack()   //退回
                R.id.reload -> webView.reload()  //刷新
                R.id.forward -> webView.goForward()   //前进
                R.id.add_favorites -> {
                    insertFavorites(webView.url.toString(), webView.title.toString())   //添加收藏夹
                }
            }
            return@setOnNavigationItemSelectedListener true
        }

        //跳转到天气查询
        headview.findViewById<RelativeLayout>(R.id.weather1).setOnClickListener {
            val intent = Intent(context, sjh_WeatherActivity::class.java).apply {
                putExtra("location_lng", place?.location?.lng)
                putExtra("location_lat", place?.location?.lat)
                putExtra("place_name", place?.name)
            }
            startActivity(intent)
        }

        //NavigationView中的item点击事件
        navView.setNavigationItemSelectedListener {
            when(it.itemId){
                R.id.favorites -> {
                    val intent = Intent(this, sjh_FavoritesActivity::class.java)
                    startActivityForResult(intent, 1)
                }
            }
            return@setNavigationItemSelectedListener true
        }

        //下拉刷新页面
        swipeRefresh.setColorSchemeResources(R.color.light_gray)
        swipeRefresh.setOnRefreshListener {
            refresh(webView)
        }

        //长按下载图片
        webView.setOnLongClickListener(View.OnLongClickListener {
            //判断是否获取了对应的写文件权限
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 2)
            } else {
                writeImage()
            }
            return@OnLongClickListener true
        })
    }

    //线程刷线，与下拉配合
    private fun refresh(webView: WebView){
        thread {
            Thread.sleep(1000)
            runOnUiThread{
                webView.reload()
                swipeRefresh.isRefreshing = false
            }
        }
    }

    //回退功能，防止按一下回退退出程序
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if(event?.keyCode == KeyEvent.KEYCODE_BACK){
            if(webView.canGoBack()) {
                webView.goBack()
                return true;
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    //点击收藏，加入到数据库中
    private fun insertFavorites(url: String, title: String) {
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                        .url("http://192.168.43.227:8888/insert?url=$url&title=$title")
                        .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null){
                    Looper.prepare();
                    Toast.makeText(this, responseData, Toast.LENGTH_SHORT).show()  //弹出页面返回信息（已收藏/收藏成功）
                    Looper.loop();
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //点击收藏夹中的url后，返回时收起NavigationView
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            1 -> if (resultCode == RESULT_OK) {
                drawLayout.closeDrawer(navView)   //NavigationView收起
                webView.loadUrl(data?.getStringExtra("url").toString())  //加载收藏夹中的网页
            }
        }
    }

    //对定位权限获取的返回结果进行处理
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            //定位权限
            1 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getcity()
                } else {
                    Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show()
                }
            }
            //文件写入权限
            2 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    writeImage()
                } else {
                    Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    //定位获取
    fun getcity(){
        mLocationClient = LocationClient(applicationContext)
        mLocationClient!!.registerLocationListener(myListener)
        val option = LocationClientOption()
        option.setIsNeedAddress(true)
        option.setNeedNewVersionRgc(true)
        option.locationMode = LocationClientOption.LocationMode.Hight_Accuracy
        option.setCoorType("GCJ02")
        option.setOpenGps(true)
        option.setScanSpan(1000 * 60 * 60);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效
        mLocationClient!!.locOption = option
        mLocationClient!!.start()
    }


    //内部类
    inner class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            //线程更新UI
            runOnUiThread {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                val addr = location.addrStr //获取详细地址信息
                val city = location.city //获取城市
                val latitude = location.latitude //获取纬度信息
                val longitude = location.longitude //获取经度信息
                header.city.text = city
                place = Place(city, Location(longitude.toString(),latitude.toString()),addr)
                thread {
                    try {
                        val client = OkHttpClient()
                        val request = Request.Builder()
                            .url("https://api.caiyunapp.com/v2.5/prhlHM2ACV6jI7wI/$longitude,$latitude/realtime.json").build()
                        val response = client.newCall(request).execute()
                        val responseData = response.body?.string()
                        if (responseData != null) {
                            parseJSONWithJSONObject(responseData)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    //内部类，下载文件时，跳转至系统浏览器进行下载
    inner class MyWebViewDownLoadListener : DownloadListener {
        override fun onDownloadStart(
            url: String, userAgent: String, contentDisposition: String, mimetype: String,
            contentLength: Long
        ) {
            val uri = Uri.parse(url)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
    }


    //解析json格式，提取温度、天气状况及对应图标
    private fun parseJSONWithJSONObject(jsonData: String) {
        runOnUiThread {
            try {
                val jsonb = JSONObject(jsonData)
                val result = jsonb.getJSONObject("result")
                val resultObject = result.getJSONObject("realtime")
                val nowtemperature = resultObject.getString("temperature")
                val nowsky_text = getSky(resultObject.getString("skycon")).info
                val nowsky_image = getSky(resultObject.getString("skycon")).icon
                header.temperature.text = nowtemperature
                header.weather_text.text = nowsky_text
                header.weather_image.setImageResource(nowsky_image)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }



    private fun writeImage(){
        val hitTestResult: WebView.HitTestResult = webView.hitTestResult
        // 如果是图片类型或者是带有图片链接的类型
        if (hitTestResult.type == WebView.HitTestResult.IMAGE_TYPE || hitTestResult.type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
            //弹出提示栏
            AlertDialog.Builder(this@sjh_MainActivity).apply {
                setTitle("提示")
                setMessage("保存图片到本地")
                setCancelable(true)
                setPositiveButton("确认") { dialog, which ->
                    val picUrl = hitTestResult.extra //获取图片链接
                    val helper = sjh_SDFileHelper(this@sjh_MainActivity)
                    val name = helper.getPicNameFromPath(picUrl.toString())   //获取图片名字+后缀 //保存图片到相册
                    Log.d("222", name.toString())
                    if (name != null) {
                        helper.savePicture(name, picUrl)   //保存图片
                        //通知图库更新
                        sendBroadcast(
                            Intent(
                                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(
                                    "file://" + Environment.getExternalStorageDirectory()
                                        .getCanonicalPath()
                                        .toString() + "/Pictures"
                                )
                            )
                        )
                    }
                }
                setNegativeButton("取消") { dialog, which ->
                }
                show()
            }
        }
    }
}